package com.sc.nft.config.fulu;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Stopwatch;
import com.sc.nft.config.fulu.model.FuLuBaseResponse;
import com.sc.nft.exception.FuLuRuntimeException;
import lombok.experimental.UtilityClass;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 福禄
 *
 * @author liGen
 * @version 1.0
 * @date 2023/11/6 3:35 下午
 */
@UtilityClass
public class FuLuHttpClient {

    private static Logger log = LoggerFactory.getLogger(FuLuHttpClient.class);

    public static final String UTF_8 = "UTF-8";


    public FuLuBaseResponse sendRequest(String url, String jsonParams) {
        log.info(String.format("请求url：%s", url));
        log.info(String.format("请求入参：%s", jsonParams));
        CloseableHttpClient httpClient = HttpClients.createDefault();
        Stopwatch stopwatch = Stopwatch.createStarted();
        try {
            HttpPost postRequest = new HttpPost(url);

            postRequest.setHeader("Content-Type", "application/json;charset=utf-8");
            StringEntity stringEntity = new StringEntity(jsonParams, UTF_8);
            postRequest.setEntity(stringEntity);
            HttpResponse response = httpClient.execute(postRequest);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                throw new RuntimeException("请求结果异常 : " + response.getStatusLine().getStatusCode());
            }
            String output = EntityUtils.toString(response.getEntity(), UTF_8);
            log.info("福禄请求地址:{},耗时:{}, 参数:{}, 返回信息:{}", url, stopwatch.elapsed(TimeUnit.MILLISECONDS), jsonParams, output);
            FuLuBaseResponse baseResponse = JSON.parseObject(output, FuLuBaseResponse.class);
            if (!baseResponse.success()) {
                throw new FuLuRuntimeException(baseResponse.getCode(), baseResponse.getMessage(), baseResponse.getResult());
            }
            return baseResponse;
        } catch (IOException e) {
            log.info("福禄请求地址:{},耗时:{}, 参数:{}", url, stopwatch.elapsed(TimeUnit.MILLISECONDS), jsonParams);
            throw new RuntimeException("POST调用异常", e);
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
